package com.example.javaffmpeg.timer;

import com.example.javaffmpeg.bean.Room;
import com.example.javaffmpeg.config.RoomsConfig;
import com.example.javaffmpeg.utils.FileUtil;
import com.github.jazzhow.command4j.CommandManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyTimer {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    public static ConcurrentHashMap<String, Object> processMap = new ConcurrentHashMap();
    @Autowired
    private RoomsConfig roomsConfig;
    @Autowired
    private CommandManager commandManager;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void sendWaterDataTask() {
        LocalDateTime nowd = LocalDateTime.now().minusMinutes(3);
        for (String key : processMap.keySet()) {
            // 如果没有时间 存在时间
            if (processMap.get(key) != null && !"null".equals(processMap.get(key)) && ((LocalDateTime) processMap.get(key)).isBefore(nowd)) {
                processMap.put(key, "null");
                Room room = roomsConfig.getMap().get(key);
                for (int i = 0; i < room.getEquipmentUrl().size(); i++) {
                    String channal = room.getName() + i + "video.m3u8";
                    try {
                        commandManager.destroy(channal);
                    } catch (Exception e) {
                        log.info(channal + "-----关闭失败-----" + e.getMessage());
                    }

                }

            }
        }

    }

    //定期清理
    @Scheduled(cron = "0 0 2 * * ?")
    public void deleteFile() {
        try {
            commandManager.destroyAll();
            FileUtil.deleteDirectory(roomsConfig.getRootUrl() + ":/nginx/html/hls");
        } catch (Exception e) {
            log.info(e + "-----关闭失败-----" + e.getMessage());
        }

    }
}
